'use client';

import type { IPagination, IPost, ISectionDetails } from '@/interfaces';
import { useContext, useEffect, useState } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import {
  clientQueryAllPost,
  clientQuerySectionDetailsById,
} from '@/services/api';
import {
  getGivenTranslatedFields,
  getUserAvatar,
  toRelativeTime,
} from '@/lib/tool';
import useToast from '@/hooks/useToast';
import PostHome from '@/app/[locale]/home/post';
import type { IHomePageContext } from '@/contexts/home';
import { HomePageContext } from '@/contexts/home';
import LeftHome from '@/app/[locale]/home/left';
import RightHome from '@/app/[locale]/home/right';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import H5Box from '@/app/[locale]/common/other/h5';
import Image from 'next/image';
import SectionGroupHomeH5Page from '@/app/[locale]/mobile/home/sectionGroup';
import SectionHomeH5Page from '@/app/[locale]/mobile/home/section';
import { AppContext } from '@/contexts/app';
import PostHomeH5Page from '@/app/[locale]/mobile/home/post';

export default function HomePage({
  source,
  translatedFields,
}: IHomePageContext) {
  const { show } = useToast();
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;

  const [pages, setPages] = useState<IPost[]>(
    source.sectionDetails
      ? source.sectionDetails.data!.content
      : source.posts.content,
  );

  const clientQuerySectionDetailsByIdQuery = useInfiniteQuery(
    [
      '/forum',
      '/sections',
      '/client',
      source.sectionDetails?.basic.id,
      '/details',
      'infinite',
    ],
    async (context) => {
      return (await clientQuerySectionDetailsById({
        id: context.queryKey[3],
        query: context.pageParam,
      })) as ISectionDetails;
    },
    {
      enabled: !!source.sectionDetails,
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (!firstPage.data!.pageable.previous) {
          return;
        }
        return {
          page: Math.max(firstPage.data!.pageable.page - 1, 0),
        };
      },
      getNextPageParam: (lastPage) => {
        if (!lastPage.data!.pageable.next) {
          return;
        }
        return {
          page: Math.min(
            lastPage.data!.pageable.page + 1,
            lastPage.data!.pageable.pages,
          ),
        };
      },
      initialData: () => {
        if (!source.sectionDetails) {
          return;
        }

        return {
          pages: [source.sectionDetails!],
          pageParams: [{ page: 0 }],
        };
      },
    },
  );
  const clientQueryAllPostQuery = useInfiniteQuery(
    ['/forum', '/posts', '/client', 'infinite'],
    async (context) => {
      return (await clientQueryAllPost({
        query: context.pageParam,
      })) as IPagination<IPost>;
    },
    {
      enabled: !source.sectionDetails,
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (!firstPage.pageable.previous) {
          return;
        }
        return {
          page: Math.max(firstPage.pageable.page - 1, 0),
        };
      },
      getNextPageParam: (lastPage) => {
        if (!lastPage.pageable.next) {
          return;
        }
        return {
          page: Math.min(lastPage.pageable.page + 1, lastPage.pageable.pages),
        };
      },
      initialData: () => {
        return {
          pages: [source.posts],
          pageParams: [{ page: 0 }],
        };
      },
    },
  );

  useEffect(() => {
    function handlePosts(data: IPagination<IPost>[]) {
      return data
        .flatMap((item) => item.content)
        .map((item) => {
          item._contentUpdatedOnText = toRelativeTime(item.contentUpdatedOn);
          return item;
        });
    }

    if (source.sectionDetails && clientQuerySectionDetailsByIdQuery.data) {
      setPages(
        handlePosts(
          clientQuerySectionDetailsByIdQuery.data.pages.map(
            (value) => value.data!,
          ),
        ),
      );
    } else if (clientQueryAllPostQuery.data) {
      setPages(handlePosts(clientQueryAllPostQuery.data.pages));
    }
  }, [
    clientQueryAllPostQuery.data,
    clientQuerySectionDetailsByIdQuery.data,
    source.sectionDetails,
  ]);

  async function onClickLoadMore() {
    try {
      if (source.sectionDetails) {
        await clientQuerySectionDetailsByIdQuery.fetchNextPage();
      } else {
        await clientQueryAllPostQuery.fetchNextPage();
      }
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <HomePageContext.Provider
      value={{
        source,
        translatedFields,
      }}
    >
      <LeftHome />
      <div className="d-none d-lg-block col mt-4 overflow-hidden">
        <div className="vstack gap-4 mx-4">
          {pages.length > 0 && (
            <>
              <PostHome
                items={pages}
                translatedFields={getGivenTranslatedFields(
                  ['comment', 'reply'],
                  translatedFields,
                )}
              />

              <LoadMoreBtn
                isLoading={
                  source.sectionDetails
                    ? clientQuerySectionDetailsByIdQuery.isLoading
                    : clientQueryAllPostQuery.isLoading
                }
                onClickLoadMore={onClickLoadMore}
              />
            </>
          )}

          {pages.length === 0 && <Nodata />}
        </div>
      </div>
      <RightHome />

      <H5Box>
        <div className="col py-2">
          <div className="card rounded-5 border-0">
            <div className="card-body">
              <div className="vstack gap-4">
                <div className="d-flex gap-4 justify-content-between mb-5">
                  <div className="vstack flex-grow-1 gap-2 justify-content-center">
                    {source.path.user &&
                      source.path.user.details.personalizedSignature && (
                        <div className="user-select-none">
                          {source.path.user.details.personalizedSignature}
                        </div>
                      )}

                    <div className="h4 mb-0">
                      {source.path.user
                        ? source.path.user.alias
                        : translatedFields.anonymousUser}
                    </div>
                  </div>
                  <Image
                    className="rounded-4"
                    src={
                      getUserAvatar(source.path.user, metadata).mediumAvatarUrl
                    }
                    alt="avatar"
                    width={56}
                    height={56}
                    placeholder="blur"
                    blurDataURL={metadata.env.APP_BLUR_DATA_URL}
                  />
                </div>

                <SectionGroupHomeH5Page />
                <SectionHomeH5Page />

                <PostHomeH5Page items={pages} />

                <LoadMoreBtn
                  isLoading={
                    source.sectionDetails
                      ? clientQuerySectionDetailsByIdQuery.isLoading
                      : clientQueryAllPostQuery.isLoading
                  }
                  onClickLoadMore={onClickLoadMore}
                />
              </div>
            </div>
          </div>
        </div>
      </H5Box>
    </HomePageContext.Provider>
  );
}

const LoadMoreBtn = ({
  onClickLoadMore,
  isLoading,
}: {
  onClickLoadMore: () => void;
  isLoading: boolean;
}) => {
  return (
    <div className="row mt-4 mb-3">
      <div className="col">
        <button
          onClick={onClickLoadMore}
          disabled={isLoading}
          type="button"
          className="btn rounded-pill text-secondary-emphasis w-100"
        >
          {isLoading ? <Spinner /> : <i className="bi bi-three-dots"></i>}
        </button>
      </div>
    </div>
  );
};
